/**
 * ajax.search.jax
 * Business Logic:
 * 		Step 01: get userId from login 
 * 		Step 02: call service to get user info based on userId
 * 		Step 03: load map with user logged in
 * 		Step 04: get list of friends when user clicks search (pagination)
 * 		Step 05: update map
 * Author: Phu
 * Date: May 28, 2014
 */
var map;
var offset = -1;
var home_position;
var userId = '';
var markers = Array();
var infoWindows = Array();
var lables = Array();
var currentTextSearch = '';

/**
 * After Login.
 */
function afterLogin() {
	// Step 01: load map
	google.maps.event.addDomListener(window, 'resize', initMap);
	google.maps.event.addDomListener(window, 'load', initMap);

	// //Step 02: load info for the first time log in
	initMap();
}

/**
 * Load map more 
 */
function loadMapMore(users) {
	
	// Set the last users
	for ( var i = 0; i < users.length; i++) {
		var user = users[i];
		var avatar = getAvatar(user);
		var image = getIcon(avatar);
		var position = getLatLng(user.located);
		var marker = new google.maps.Marker({
		     position: position,
		     map: map,
		     icon: image,
		     title: user.username,
		     draggable: true,
		     infoWindowIndex : i+(offset*MAX_PAGE+1)
		 });
		
	    var label = new Label({
	        map: map,
	        title: user.fullname
	      });
	    label.bindTo('position', marker, 'position');
	    label.bindTo('text', marker, 'position');
	    
	    var info = getPopupInfo(user);
	    infoWindow = new google.maps.InfoWindow({
			content : info
		});
		google.maps.event.addListener(marker, "click",function(e) {
							infoWindows[this.infoWindowIndex].open(map, this);
						});
		infoWindows.push(infoWindow);
		markers.push(marker);
		lables.push(label);
	}
	
}

function updateUser() {
	//load user account from cookie
	//var userId = $.cookie('userId');
	var textSearch = $('#textSearch').val();
	if (userId != '' && userId != null) {
		$.ajax({
			url : "/search?action=getUsersByIndex&userId="+userId+"&textSearch="+currentTextSearch+"&offset="+offset,
			type: 'GET',
	        data: '',
			success : function(resp) {
				if (resp != null) {
					// getting the data from the response object
					var data = resp.data;
					
					//initialize map
					if(data.length > 0) {
						loadMapMore(data);
					}
					else {
						alert('No record found more');
						$("#searchButton").html('Go');
					}
						
				}
			},
			error : function(resp){
				alert('Cannot get data! Please check again');
				$("#searchButton").html('More');
			}
		});
	} else {//not login
		//Go to index page
		document.location.href = '/index.html';
	}
}

/**
 * Load first user
 */
function loadMap(user) {
	//Get user login to initialize map
	markers = Array();
	infoWindows = Array();
	lables = Array();
	
	//Set profile
	setProfile(user);
	
	//set map options
	var mapOptions
	if (user.located == NULL) {
		mapOptions = {
				zoom : 8,
				center : new google.maps.LatLng(40.111689,-78.134766),//new york
				mapTypeId : google.maps.MapTypeId.ROADMAP
			};
		home_position = new google.maps.LatLng(40.111689,-78.134766);
	} else {
		home_position = getLatLng(user.located);
		mapOptions = {
				zoom : 8,
				center : home_position,
				mapTypeId : google.maps.MapTypeId.ROADMAP
			};
	}
	
	//load map with user's position
	map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
	
	var avatar = getAvatar(user);
	var image = getIcon(avatar);
	
	var marker = new google.maps.Marker({
	     position: home_position,
	     map: map,
	     icon: image,
	     title: user.username,
	     draggable: true,
//	     animation: google.maps.Animation.BOUNCE,
	     infoWindowIndex : offset
	});
	
	var label = new Label({
	    map: map,
	    title: user.fullname
	});
	label.bindTo('position', marker, 'position');
	label.bindTo('text', marker, 'position');
	
	var info = getPopupInfo(user);
	var infoWindow = new google.maps.InfoWindow({
		content : info
	});
	google.maps.event.addListener(marker, "click", 
			function(e) {
				infoWindows[this.infoWindowIndex].open(map, this);
			});
	infoWindows.push(infoWindow);
	markers.push(marker);
	lables.push(label);
}


/**
 * load current user logged in phonemap
 */
function loadUser() {
	$.ajax({
		url : "/search?action=initMap&userId="+userId,
		type: 'GET',
        data: '',
		success : function(resp) {
			if (resp != null) {
				// getting the data from the response object
				var data = resp.data;
				//initialize map
				if(data.length > 0) {
					//load map with current user
					loadMap(data[0]);
				}
			}
		},
		error : function(resp){
			alert('Cannot get data! Please check again');
		}
	});
}

/**
 * Load map
 */
function initMap() {
	offset = -1;
	userId = $.cookie('useraccount');
	if (userId != '' && userId != null) {
		//load current user with map
		loadUser();
	} else {
		//Go to index page
		document.location.href = '/index.html';
	}
}

function moveMapToFirtMaker() {
	map.panTo(home_position);
}

//Removes the overlays from the map, but keeps them in the array
/**
 * Clear overlays.
 */
function clearOverlays() {
  if (markers) {
    for (i in markers) {
    	markers[i].setMap(null);
    	lables[i].onRemove();
    }
    markers = new Array();
    infoWindows = new Array();
    lables = new Array();
  }
}	

function updateMap() {
	var searchButton = $("#searchButton").html();
	if ($('#textSearch').val() != null && $('#textSearch').val() != '') {
		if (searchButton === 'Go') {
			offset = 0;
			currentTextSearch = $('#textSearch').val();
			$("#searchButton").html('More');
			clearOverlays();
		} else {
			offset = offset + 1;
		}
		updateUser();
	}	
}
	
	




